<script setup>
import {ref, onMounted, computed} from 'vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'
import { updateUserInfo } from '@/api/user'
import { Plus, User, Coin, Star, Trophy, MagicStick } from "@element-plus/icons-vue"
import router from "@/router"

const icons = {
  User,
  Coin,
  Star,
  Trophy
}
const userInfoStore = useUserInfoStore()

const form = ref({
  id: null,
  username: '',
  phone: '',
  email: '',
  gender: 0,
  birthday: '',
  avatar: '',
  levelId: null,
  discountRate: 1.0,
  pointsMultiplier: 1.0,
  points: 0,
  balance: 0.0,
  totalConsumption: 0.0,
})

const genderOptions = [
  { label: '保密', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]

onMounted(() => {
  const u = userInfoStore.userInfo
  if (!u) return
  Object.assign(form.value, {
    id: u.id,
    username: u.username,
    mobile: u.mobile,
    email: u.email,
    gender: u.gender,
    birthday: u.birthday,
    avatar: u.avatar,
    levelId: u.levelId,
    discountRate: u.discountRate,
    pointsMultiplier: u.pointsMultiplier,
    points: u.points,
    balance: u.balance,
    totalConsumption: u.totalConsumption
  })
})

const submit = async () => {
  const res = await updateUserInfo(form.value)
  if (res.status === true) {
    ElMessage.success('保存成功')
    userInfoStore.fetchUserInfo?.()
  } else {
    ElMessage.error('保存失败')
  }
}

const imageUrl = ref('')

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  form.value.avatar = response.data.url
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const backShopping = () => {
  router.push('/shopping')
}

// 等级配置
const levelConfig = {
  1: {
    name: '银米',
    tagType: 'info',
    bgColor: '#f0f9eb',
    textColor: '#67c23a',
    icon: User
  },
  2: {
    name: '金米',
    tagType: '',
    bgColor: '#f4f4f5',
    textColor: '#909399',
    icon: Coin
  },
  3: {
    name: '白金米',
    tagType: 'warning',
    bgColor: '#fdf6ec',
    textColor: '#e6a23c',
    icon: Star
  },
  4: {
    name: '钻石米',
    tagType: '',
    bgColor: '#f0f4ff',
    textColor: '#409eff',
    icon: Trophy
  },
  5: {
    name: '至尊钻石米',
    tagType: 'danger',
    bgColor: '#fef0f0',
    textColor: '#f56c6c',
    icon: MagicStick
  }
}

// 获取当前等级配置
const currentLevelConfig = computed(() => {
  return levelConfig[form.value.levelId] || levelConfig[1]
})

onMounted(() => {
  userInfoStore.fetchUserInfo()
})

</script>

<template>
  <div class="user-profile-container">
    <div class="header">
      <el-button type="primary" plain @click="backShopping">
        <el-icon><ArrowLeft /></el-icon>
        返回主会场
      </el-button>
      <h1 class="title">个人资料中心</h1>
    </div>

    <el-card class="profile-card">
      <div class="card-content">
        <!-- 左侧头像区域 -->
        <div class="avatar-section">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <!-- 修改后的逻辑：如果有头像则显示头像，否则显示上传图标 -->
            <img
                v-if="form.avatar"
                :src="form.avatar"
                class="avatar"
            />
            <div v-else class="avatar-placeholder">
              <el-icon class="avatar-uploader-icon">
                <Plus />
              </el-icon>
              <span class="upload-text">上传头像</span>
            </div>
          </el-upload>
          <div class="user-level">
            <el-tag
                :type="currentLevelConfig.tagType"
                size="large"
                :style="{
        backgroundColor: currentLevelConfig.bgColor,
        color: currentLevelConfig.textColor,
        borderColor: currentLevelConfig.textColor
      }"
            >
              <el-icon class="level-icon">
                <component :is="currentLevelConfig.icon" />
              </el-icon>
              {{ currentLevelConfig.name }} (VIP{{ form.levelId || 1 }})
            </el-tag>
          </div>
        </div>

        <!-- 右侧表单区域 -->
        <div class="form-section">
          <el-form
              :model="form"
              label-width="100px"
              label-position="left"
              class="profile-form"
          >
            <div class="form-grid">
              <div class="form-column">
                <el-form-item label="用户名" class="form-item">
                  <el-input v-model="form.username" placeholder="请输入用户名" />
                </el-form-item>

                <el-form-item label="手机号" class="form-item">
                  <el-input v-model="form.mobile" placeholder="请输入手机号" />
                </el-form-item>

                <el-form-item label="邮箱" class="form-item">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>

                <el-form-item label="性别" class="form-item">
                  <el-radio-group v-model="form.gender">
                    <el-radio
                        v-for="opt in genderOptions"
                        :key="opt.value"
                        :label="opt.value"
                        class="gender-radio"
                    >
                      {{ opt.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>

              <div class="form-column">
                <el-form-item label="生日" class="form-item">
                  <el-date-picker
                      v-model="form.birthday"
                      type="date"
                      placeholder="选择生日"
                      style="width: 100%"
                      value-format="YYYY-MM-DD"
                  />
                </el-form-item>

                <el-form-item label="账户余额" class="form-item">
                  <el-input
                      v-model="form.balance"
                      disabled
                      class="money-input"
                  >
                    <template #append>元</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="积分" class="form-item">
                  <el-input
                      v-model="form.points"
                      disabled
                      class="points-input"
                  >
                    <template #append>积分</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="累计消费" class="form-item">
                  <el-input
                      v-model="form.totalConsumption"
                      disabled
                      class="money-input"
                  >
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>

            <div class="form-actions">
              <el-button
                  type="primary"
                  size="large"
                  @click="submit"
                  class="submit-btn"
              >
                保存修改
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style>
.user-profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 20px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.profile-card {
  background-image: url('@/assets/IMG_20250630_185554.png'); /* 替换为你的图片路径 */
  background-size: cover;
  background-position: center;
  opacity: 1; /* 控制透明度，避免遮挡文字 */
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.card-content {
  display: flex;
  gap: 40px;
  padding: 24px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 220px;
  flex-shrink: 0;
}

.avatar-uploader {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  border: 1px dashed #dcdfe6;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #8c939d;
}

.avatar-uploader-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.user-level {
  margin-top: 12px;
}

.form-section {
  flex: 1;
}

.profile-form {
  width: 100%;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-column {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  margin-bottom: 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.submit-btn {
  width: 180px;
  height: 40px;
  font-size: 16px;
}

.gender-radio {
  margin-right: 20px;
}

.money-input,
.points-input {
  :deep(.el-input__inner) {
    text-align: right;
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .card-content {
    flex-direction: column;
  }

  .avatar-section {
    width: 100%;
    margin-bottom: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 576px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .title {
    font-size: 20px;
  }

  .card-content {
    padding: 16px;
  }

  .submit-btn {
    width: 100%;
  }
}

.user-level {
  margin-top: 12px;
}

.level-icon {
  margin-right: 6px;
  font-size: 16px;
  vertical-align: middle;
}

.el-tag {
  transition: all 0.3s;
  font-weight: 500;
  padding: 8px 12px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
}

.level-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  height: auto;
  line-height: 1.5;
}

.level-icon {
  margin: 0;
  font-size: 16px;
}

</style>
